const service = require('../service/frontService')
const adminService = require('../service/loginService')
const articleService = require('../service/articleService')
const talkService = require('../service/talkService')
const commentService = require('../service/commentService')
const messageService = require('../service/messageService')
const emailerService = require('../service/emailerService')

// 引入jwt模块
const jwt = require('../util/jwt.js')
const controller = {
  async updateMessage (req, res) {
    let id = '1'
    let data = await service.updateMessage(id, req.body)
    if (data.acknowledged) {
      res.send({ ok: 1, info: '修改成功' })
    } else {
      res.send({ ok: 0, info: '修改失败你有可能创建的' })
    }
  },
  //  获取到首页的信息
  async getMessage (req, res) {
    let data = await service.getMessage()
    res.send({ ok: 1, info: data })
  },
  //  获取到首页center的信息
  async getCenter (req, res) {
    let data = await service.getCenter()
    let [adminAvatar] = await adminService.findMain()
    res.send({ ok: 0, info: [...data, { adminAvatar: adminAvatar?.avatar }] })
  },
  //  修改个人介绍
  async updateCenter (req, res) {
    let id = '1'
    let { wechat, token, tel, qq, motto, uname, location } = req.body
    username = jwt.verify(token)?.uname
    if (username == 'admin') {
      let data = await service.updateCenter(id, {
        tel,
        qq,
        motto,
        wechat,
        uname,
        location,
      })
      if (data.acknowledged) {
        res.send({ ok: 1, info: '修改成功' })
      } else {
        res.send({ ok: 0, info: '修改失败' })
      }
    } else {
      res.send({ ok: 0, code: 401, info: '你不是超级管理员哦！！！' })
    }
  },
  // 把首页数据发回去
  async endfinAll (req, res) {
    let data = await Promise.all([
      articleService.endfinAll(),// 文章数量
      talkService.endfinAll(), // 动态数量
      commentService.endfinAll(), //评论数量
      messageService.endfinAll(), //留言数量
      emailerService.endfinAll(), //用户数量
      articleService.getVists(), // 访问量
    ])
    res.send(data)

  },

}

module.exports = controller
